package com.book.service.impl;

import cn.hutool.core.date.DateUtil;
import com.book.core.exception.FileUpException;
import com.book.service.FileService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service("minioFileService")
//@Primary
@RequiredArgsConstructor
public class MinioFileServiceImpl implements FileService {
    private final MinioClient minioClient;
    @Value("${app.file.prefix}")
    private  String prefix;
    @Override
    public String uploadFile(MultipartFile file, String bucketName) throws FileUpException {
        String timeDir = DateUtil.format(DateUtil.date(), "yyyy-MM");
        String originalFilename = file.getOriginalFilename();
        String objectName = bucketName + "/" + timeDir + "/" + originalFilename;
        try (InputStream inputStream = file.getInputStream()) {
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build());
            if (!isExist) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
            }
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, file.getSize(), -1) // -1表示分片大小默认
                            .contentType(file.getContentType())
                            .build()
            );
            return prefix+"/" + bucketName + "/" + timeDir + "/" + originalFilename;

        } catch (Exception e) {
            throw new FileUpException("MinIO文件上传失败: " + e.getMessage());
        }
    }
}
